const { WX } = require('weixin-nodejs')

// 启动配置文件
const dotenv = require('dotenv')
dotenv.config()

// 中间件
const WebSocketServer = require('./lib/WebScoketServer')
const router = require('./router')
const koa_static = require('koa-static')

const path = require('path')

const wx = new WX({
  token: process.env.token,
  port: process.env.port,
  appid: process.env.appid,
  secret: process.env.secret,
  plugin_path: path.join(__dirname, 'plugins'),
  sotre_path: path.join(__dirname, 'stores'),
})

/** 启动 wws 服务 */
const wss = new WebSocketServer(process.env.wssport)
// 404 处理
wx.koa.use(require('./middleware/404'))
// 启动静态资源服务
wx.koa.use(koa_static('./public'))
// 允许跨域
wx.koa.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (ctx.method == 'OPTIONS') {
    ctx.body = 200;
  } else {
    await next();
  }
});
// 启动路由
wx.koa.use(router.routes())
wx.koa.use(router.allowedMethods())

module.exports = { wss, wx }


